﻿using System;
using System.Collections.Generic;
using System.Linq;
using Best.SmartCms.Common;
using Best.SmartCms.Dao.Common;
using Best.SmartCms.Domain;
using Best.SmartCms.Dto.Request;
using Best.SmartCms.Dto;

namespace Best.SmartCms.Dao
{
    /// <summary>
    /// Category数据库操作类
    /// </summary>
    public class CategoryDao : BaseDao<Category>, ICommonDao
    {
        private readonly MySqlDbContext _db;

        public CategoryDao(MySqlDbContext dbContext) : base(dbContext)
        {
            _db = dbContext;
        }


        public Category FindById(long id)
        {
            return _db.CategorySet.FirstOrDefault(p => p.Id == id);
        }

        public List<Category> List()
        {
            var result = _db.CategorySet.AsQueryable();
            // 排序
            result = result.OrderBy(p => p.OrderNo);
            return result.ToList();
        }

        public List<Category> ListByParentId(long parentid)
        {
            var result = _db.CategorySet.Where(p => p.ParentId == parentid);
            // 排序
            result = result.OrderBy(p => p.OrderNo);
            return result.ToList();
        }

        public List<Category> PageList(CategoryListQueryDto query, out int totalCount, out int totalPages)
        {
            var result = _db.CategorySet.AsQueryable();
            if (!string.IsNullOrEmpty(query.Keywords))
            {
                result = result.Where(d => d.Name.Contains(query.Keywords));
            }

            // 排序
            result = result.OrderBy(p => p.OrderNo);
            return result.PageBy(query.PageIndex, query.PageSize, out totalPages, out totalCount)
                .ToList();
        }
    }
}
